package util

import (
	"math/rand"
	"strings"
	"time"

	"github.com/micro-plat/lib4go/security/rsa"
	"github.com/micro-plat/lib4go/types"
)

//CheckInMap 检查map中是否存在某键值对，值不能为空
func CheckInMap(key string, input map[string]interface{}) bool {
	if key == "" || input == nil {
		return false
	}

	v, ok := input[key]
	if !ok || v == nil {
		return false
	}

	return true
}

//CheckInArray 检查数组中是否存在某元素
func CheckInArray(value string, input []string) bool {
	if value == "" || len(input) == 0 {
		return false
	}

	for _, v := range input {
		if v == value {
			return true
		}
	}

	return false
}

//GetSecret 获取l位随机数字的字符串密钥
func GetSecret(l int) string {
	str := "00112233445566778899qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

//GetSecretExtra .
func GetSecretExtra(l int) string {
	nanoTime := types.GetString(time.Now().Nanosecond())
	return MD5(nanoTime)
}

//GenRsaKey RSA密钥对生成
func GenRsaKey(pkcsType string, bits int) (pubKey, priKey string, err error) {
	priKey, pubKey, err = rsa.GenerateKey(strings.ToUpper(pkcsType), bits)
	return
}
